package com.itheima.admin.gateway.filter;


import cn.hutool.core.util.StrUtil;
import com.itheima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorizeFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2. 查看请求对象是否是发往登录微服务的请求
        if (request.getURI().getPath().contains("/login/in")){
            //2.1 是; 则放行
            return chain.filter(exchange);
        }

        //3. 获取当前请求对象中的请求头信息
        HttpHeaders headers = request.getHeaders();

        //4. 判断请求头信息中是否存在token
        String token = headers.getFirst("token");
        if (StrUtil.isEmpty(token)){
            //5 不存在
            //5.1 向客户端返回401
                //设置响应401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //向客户端返回
            return response.setComplete();
        }
        try {
            //6. 存在
            //6.1 调用工具类进行解析; 判断token是否有效
            //6.1.1 获取token中的Payload部分
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int verifyToken = AppJwtUtil.verifyToken(claims);

            //判断token是否还有效
            if (verifyToken == -1 || verifyToken == 0){
                //8. 有效; 则向设置新的请求路径
                //8.1 获取id
                Integer id = (Integer) claims.get("id");

                //当为true时, 表示token即将过期
                if (verifyToken == 0){
                    // 重新创建一个token
                    String token1 = AppJwtUtil.getToken(id.longValue());
                    //将token添加进响应头中
                    response.getHeaders().add("token",token1);
                }

                //8.2 将id添加进请求路径中
                ServerHttpRequest httpRequest = request.mutate().headers(
                        httpHeaders -> httpHeaders.add("userId", id + "")
                ).build();
                //8.3 设置新的请求路径
                exchange.mutate().request(httpRequest).build();
            }

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //放行
        return chain.filter(exchange);
    }
}
